﻿#include <QPainter>
#include <QPolygon>
#include "JZImageLabel.h"

//JZImageLabel
JZImageLabel::JZImageLabel(QWidget *parent)
    :QWidget(parent)
{

}

JZImageLabel::~JZImageLabel()
{

}

QImage JZImageLabel::image()
{
    return m_image;
}

void JZImageLabel::setImage(QImage image)
{
    m_image = image;
    m_graphList.clear();
    updatePixmap();
}

void JZImageLabel::setGraphics(const QList<JZGraphic> &graphList)
{
    m_graphList = graphList;
    updatePixmap();
}

const QList<JZGraphic> &JZImageLabel::graphics()
{
    return m_graphList;
}

void JZImageLabel::addGraphics(JZGraphic g)
{
    m_graphList.push_back(g);
    updatePixmap();
}

void JZImageLabel::clearGraphic()
{
    setGraphics(QList<JZGraphic>());
}

void JZImageLabel::updatePixmap()
{
    if (m_image.isNull())
    {
        m_pixmap = QPixmap();
        return;
    }

    QImage image = m_image.copy();

    QPainter painter(&image);
    for (int i = 0; i < m_graphList.size(); i++)
    {
        auto& g = m_graphList[i];
        g.draw(&painter);
    }
    m_pixmap = QPixmap::fromImage(image);
    update();
}

QSize JZImageLabel::sizeHint() const
{
    return QSize(100, 100);
}

void JZImageLabel::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.fillRect(rect(), Qt::white);
    painter.setRenderHint(QPainter::Antialiasing);

    if(!m_pixmap.isNull())
    {
        auto draw_size = m_pixmap.size().scaled(size(), Qt::KeepAspectRatio);
        QRect rc((width() - draw_size.width()) / 2, (height() - draw_size.height()) / 2, draw_size.width(), draw_size.height());
        painter.drawPixmap(rc, m_pixmap);
    }    
}